<template>
  <div>
    <el-form ref="form" :model="searchForm" inline>
      <el-form-item label="">
        <el-input v-model="searchForm.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-button @click="search" type="primary" icon="el-icon-search"
        >查询</el-button
      >
      <el-button @click="clear">清空</el-button>
    </el-form>

    <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>
    <el-button type="danger" @click="deleteAll" :disabled="!selectIds.length"
      >批量删除</el-button
    >

    <!-- 表格 -->
    <el-table
      @select="select"
      @select-all="selectAll"
      @selection-change="selectionChange"
      v-loading="loading"
      :data="userInfo.items"
      style="width: 100%; margin: 20px 0"
      border
      stripe
    >
      <el-table-column align="center" type="selection" width="80px">
      </el-table-column>
      <el-table-column align="center" type="index" label="序号" width="80px">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100px">
      </el-table-column>
      <el-table-column width="100px" prop="nickName" label="用户昵称">
      </el-table-column>
      <el-table-column width="with" prop="roleName" label="权限列表">
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="width">
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" width="width">
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button
            @click="mangerRole(row)"
            type="primary"
            size="mini"
            icon="el-icon-user"
          ></el-button>
          <el-button
            @click="edit(row)"
            type="warning"
            size="mini"
            icon="el-icon-edit"
            style="margin: 0 20px"
          ></el-button>

          <el-popconfirm title="您确定删除吗？" @onConfirm="confirmDelete(row)">
            <el-button
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="text-align: center"
      prev-text="上一页"
      next-text="下一页"
      background
      @size-change="handleSizeChange"
      @current-change="getUserList"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="userInfo.total"
    >
    </el-pagination>

    <!-- Dialog -->
    <el-dialog
      :title="userForm.id ? '编辑用户' : '添加用户'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="userForm.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-show="!userForm.id">
          <el-input v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- Dialog：给用户分配角色 -->
    <el-dialog title="设置角色" :visible.sync="roledialogFormVisible">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input
            :disabled="true"
            :value="userForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="assignRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRolesList"
              :label="role.id"
              :key="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roledialogFormVisible = false">取 消</el-button>
        <el-button :loading="roleLoading" type="primary" @click="giveUserRoles"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      checkAll: false,
      isIndeterminate: true,
      roledialogFormVisible: false,
      assignRoles: [],
      allRolesList: [],
      selectIds: [],
      loading: false,
      roleLoading: false,
      searchForm: {
        username: "",
      },
      realForm: {
        username: "",
      },
      page: 1,
      limit: 3,
      userInfo: {},
      dialogFormVisible: false,
      userForm: {
        password: "",
        nickName: "",
        username: "",
      },
      userRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    async giveUserRoles() {
      try {
        this.roleLoading = true;
        await this.$http.user.reqGiveUserRoles(
          this.userForm.id,
          this.assignRoles.toString()
        );
        this.roleLoading = false;
        this.$message({
          type: "success",
          message: "分配角色成功!",
        });

        this.getUserList(this.page);
        this.roledialogFormVisible = false;
        if (this.$store.getters.name === this.userForm.username) {
          window.location.reload();
        }
      } catch (error) {}
    },
    //点击分配角色按钮的回调
    async mangerRole(row) {
      this.userForm = row;
      let res = await this.$http.user.reqUserRoleList(row.id);
      this.assignRoles = res.data.assignRoles.map((item) => item.id);
      this.allRolesList = res.data.allRolesList;
      // console.log(res);
      this.checkAll = this.assignRoles.length == this.allRolesList.length;
      this.isIndeterminate =
        this.assignRoles.length < this.allRolesList.length &&
        this.assignRoles.length > 0;
      this.roledialogFormVisible = true;
    },
    handleCheckAllChange(val) {
      // console.log(val, 1);
      this.assignRoles = val ? this.allRolesList.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      // console.log(value, 2);
      let checkedCount = value.length;
      this.checkAll =
        checkedCount === this.allRolesList.length &&
        this.allRolesList.length > 0;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allRolesList.length;
    },
    // 批量删除
    deleteAll() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let arr = [];
          this.selectIds.forEach((item) => {
            let p = this.$http.user.reqDeleteUser(item);
            arr.push(p);
          });

          try {
            await Promise.all(arr);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getUserList(
              this.userInfo.items.length - this.selectIds.length == 0
                ? this.page - 1
                : this.page
            );
          } catch (error) {}
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    selectionChange(selection) {
      // console.log(selection, 3333);
    },

    //全选
    selectAll(selection) {
      // console.log(selection, 222);
      this.selectIds = selection.map((item) => item.id);
    },
    select(selection, row) {
      this.selectIds = selection.map((item) => item.id);
      // console.log(selection, 111, row);
    },
    //清空
    clear() {
      this.searchForm.username = "";
      this.realForm.username = "";
      this.getUserList();
    },
    // 删除
    async confirmDelete(row) {
      try {
        let res = await this.$http.user.reqDeleteUser(row.id);
        this.$message({
          type: "success",
          message: "删除成功",
        });
        this.getUserList(
          this.userInfo.items.length > 1 ? this.page : this.page - 1
        );
      } catch (error) {
        this.$message({
          type: "error",
          message: "删除失败",
        });
      }
    },
    //
   addOrUpdateUser() {
      this.$refs.userForm.validate(async(valid) => {
        if (valid) {
          try {
            let res = await this.$http.user.reqAddOrUpdateUser(this.userForm);
            this.$message({
              type: "success",
              message: this.userForm.id ? "编辑用户成功" : "添加用户成功",
            });
            this.getUserList(this.userForm.id ? this.page : 1);
            this.dialogFormVisible = false;
          } catch (error) {}
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 编辑按钮的回调
    edit(row) {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.userForm.resetFields();
        this.userForm = { ...row };
      });
    },
    //搜索的回调
    search() {
      this.realForm = { ...this.searchForm };
      this.getUserList();
    },
    //添加按钮的回调
    add() {
      this.userForm = {
        password: "",
        nickName: "",
        username: "",
      };
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.userForm.resetFields();
      });
    },
    //获取用户列表
    async getUserList(p = 1) {
      this.loading = true;
      this.page = p;
      let { page, limit } = this;
      let { username } = this.realForm;
      let res = await this.$http.user.reqUserList(page, limit, username);

      this.loading = false;
      // console.log(res.data.items);
      let adminIndex = res.data.items.findIndex(
        (item) => item.username == "admin"
      );
      // console.log(adminIndex);
      if (adminIndex != -1) {
        res.data.items.splice(adminIndex, 1);
      }
      this.selectIds = [];
      this.userInfo = res.data;
    },
    //
    handleSizeChange(limit) {
      this.limit = limit;
      this.getUserList();
    },
  },
};
</script>

<style>
</style>